﻿(function ($) {
    function MyAjaxToDo($this) {
        var url = unescape($this.attr("href")).replaceTmById($(event.target).parents(".unitBox:first"));
        DWZ.debug(url);
        if (!url.isFinishedTm()) {
            alertMsg.error($this.attr("warn") || DWZ.msg("alertSelectMsg"));
            return false;
        }
        var title = $this.attr("title");
        if (title) {
            alertMsg.confirm(title, {
                okCall: function () {
                    ajaxTodo(url, $this.attr("callback"));
                }
            });
        } else {
            ajaxTodo(url, $this.attr("callback"));
        }
        // event.preventDefault();
    }
    //注册第三方插件
    DWZ.regPlugins.push(function ($p) {
        if ($.fn.jmultLookup) $("[jmultLookup]:button", $p).jmultLookup();
        //jItemDetails
        $("table.jItemDetails", $p).each(function () {
            $.jItemDetails.init($(this));
        });
        //toFixed
        $("input[toFixed],span[toFixed]", $p).each(function () {
            $this = $(this);
            var value = $this.val() || $this.text();
            if ($.isNumeric(value)) {
                var nvalue = parseFloat(value).toFixed($this.attr("toFixed"));
                $this.val(nvalue);
                if ($this.text()) { $this.text(nvalue); }
                $this.addClass("textright");
            }
        });
        //日期格式化
        $("span[formatDate]", $p).each(function () {
            $this = $(this);
            var value = $this.val() || $this.text();
            if ($.trim(value).length > 0) { $this.text(new Date(new Date(Date.parse(value.replace(/-/g, "/")))).formatDate($this.attr("formatDate"))); }
        });
        //日期格式化
        $("input[formatDate]", $p).each(function () {
            $this = $(this);
            var value = $this.val() || $this.text();
            if ($.trim(value).length > 0) { $this.val(new Date(new Date(Date.parse(value.replace(/-/g, "/")))).formatDate($this.attr("formatDate"))); }
        });
        //下拉列表提交名称
        $("select[selectedvalue]", $p).each(function () {
            $this = $(this);
            $this.val($this.attr("selectedvalue"));
            var label = $this.find("option:selected").text() || $this.attr("selectedvalue");
            if ($this.val()) {
                $("a[name='" + $this.attr("name") + "']").html(label);
            }
        });
        //sumbitText
        $("select[sumbitText]", $p).each(function () {
            $this = $(this);
            var name = $this.attr("sumbitText");
            var defaulttext = $this.find("option:selected").text();
            var defaultvalue = $this.val();
            if ($.trim(name).length > 0) {
                var $target = $("<input type='hidden' id='" + name + "' name='" + name + "'/>");
                if (defaultvalue)
                    $target.val(defaulttext);
                $this.after($target);
                $this.change(function () {
                    var text = $(this).find("option:selected").text();
                    var val = $(this).find("option:selected").val();
                    if (val && text) { $target.val(text); }
                });
            }
        });
        //select3
        $("select.select3", $p).select3();
        //树形table
        $("table.treetable", $p).each(function () {
            $this = $(this);
            var ajax = $this.attr("ajax") || "";
            var initialState = $this.attr("initialState") || "collapsed";
            if (ajax.length == 0) {
                $this.treetable({ expandable: true, initialState: initialState });
            }
            else {
                $this.treetable({
                    expandable: true,
                    canExpand: true,
                    onNodeCollapse: function () {
                        var node = this;
                        $this.treetable("unloadBranch", node);
                    },
                    onNodeExpand: function () {
                        var node = this;

                        // Render loader/spinner while loading
                        $.ajax({
                            async: false, // Must be false, otherwise loadBranch happens after showChildren?
                            url: ajax + $(this.row).attr("rel")
                        }).done(function (html) {
                            var rows = $(html).filter("tr");
                            rows.find(".directory").parents("tr").each(function () {
                                droppableSetup.apply(this);
                            })
                            $this.treetable("loadBranch", node, rows);
                            $this.cssTable();
                        });
                    }
                });
            }
        });
        //树形table选择
        $("table.treetableSelect", $p).treetable({ expandable: true, initialState: "expanded" });
        //重置表单
        $("button[type='reset']").each(function () {
            var $this = $(this);
            var $form = $this.closest("form");
            $this.click(function () {
                $("input[type*='text']", $form).each(function () {
                    var obj = $(this);
                    obj.val("");
                });
                $("select", $form).each(function () {
                    var obj = $(this);
                    obj.val("");
                });
                $("input[type*='checkbox radio']", $form).each(function () {
                    var obj = $(this);
                    obj.attr("checked", false);
                });
                $form.submit();
            });
        });
        //a 变灰
        $("a.disabled").each(function () {
            $this = $(this);
            $this.undelegate();
            $this.unbind();
            $this.bind("click", function (event) {
                event.stopPropagation();
                return false;
            });
        });
        //回车跳转到下一个编辑框
        $("div.enableEnterToTab").each(function () {
            //var $p = $.pdialog.getCurrent() || navTab.getCurrentPanel();
            $(this).enableEnterToTab({ captureTabKey: true });
        });
        //下拉转多列
        $("select.selectToCols").each(function () {
            $(this).selectToCols();//Select转多列
        });
        //复选转多列
        $(".checkboxToCols").each(function () {
            $(this).checkboxToCols();//checkbox转多列
        });
        //input转多列
        $("input.toMutil").each(function () {
            $.toCreateMutil($(this));
        });
        $(".IsExisted").each(function () {//自定义IsExisted错误信息
            $this = $(this);
            var message = $this.attr("messages") || "记录已存在";
            $.extend($.validator.messages, {
                IsExisted: message
            });
        });

        $.validator.addMethod("IsExisted", function (value, element) {
            $this = $(element);
            var ajaxurl = $this.attr("ajaxurl") || $this.attr("ajax");
            var targeter = $this.attr("targeter");
            if (targeter) {
                var $p = $.pdialog.getCurrent() || navTab.getCurrentPanel();
                var targeterVal = $("#" + targeter + "", $p).val();
            }
            var result = false;
            $.ajax({
                type: 'POST',
                url: ajaxurl,
                dataType: "json",
                cache: false,
                async: false,
                data: { "data": value, "targeter": targeterVal },
                success: function (response) {
                    var json = DWZ.jsonEval(response);
                    if (json[DWZ.keys.statusCode] == DWZ.statusCode.ok) {
                        result = true;
                    }
                },
                error: DWZ.ajaxError
            });
            return result;
        }, "记录已存在！");
        $.validator.addClassRules({
            IsExisted: { IsExisted: true }
        });

        $.validator.addMethod("tRequired", function (value, element) {
            $this = $(element);
            $box = $.pdialog.getCurrent() || navTab.getCurrentPanel();
            var $target = $this.attr("target");
            var result = false;
            var isAll = $target.indexOf("&") >= 0;
            var targets = $target.split('|');
            var targetValue = $this.attr("targetValue");
            if (isAll) targets = $target.split('&');
            var targetObj = $("#" + targets[0], $box) || $("[name='" + targets[0] + "']", $box)
            if (targetValue && targetObj.val() == targetValue) {
                result = $.trim($this.val()).length > 0
            }
            else {
                $.each(targets, function (i, v) {
                    var val = $("#" + v, $box).val();
                    if (isAll) { result = $.trim(val).length > 0; if (!result) return false; }
                    else { result = $.trim(val).length > 0; if (result) return false; }
                });
            }
            return result;
        }, "必填");
        $.validator.addClassRules({
            tRequired: { tRequired: true }
        });
    });

    /**
         * 扩展String方法
         */
    $.extend(String.prototype, {
        replaceTmById2: function (_box) {
            var $parent = _box || $(document);
            return this.replace(RegExp("({[A-Za-z_]+[A-Za-z0-9_]*})", "g"), function ($1) {
                var $input = $parent.find("#" + $1.replace(/[{}]+/g, ""));
                return $input.length > 0 ? $input.val() : "";
            });
        },
        replaceSuffix2: function (index) {
            return this.replace('#index#', index);
        },

    });
    /***************************************
    扩展其他方法
    ****************************************/
    $.extend({
        toCreateMutil: function ($input) {
            var valstr = $input.val();
            if (valstr) {
                var valarry = valstr.split(',');
                var inputname = $input.attr("name");
                var boxname = inputname.replace(".", "_") + "spanToMutilCols";
                var $box = $("<span id='" + boxname + "'></span>");
                $("#" + boxname).remove();
                for (var i = 0; i < valarry.length; i++) {
                    var name = inputname.replace(".", "[" + i + "].");
                    var $target = $("<input type='hidden' id='" + name + "' name='" + name + "' value='" + valarry[i] + "'/>");
                    $target.appendTo($box);
                }
                $input.after($box);
            }
        }
    });
    $.fn.setDisabled = function () {
        $("a.disabled").each(function () {
            $this = $(this);
            $this.undelegate();
            $this.unbind();
            $this.bind("click", function (event) {
                event.stopPropagation();
                return false;
            });
        });
    };
})(jQuery);

